package com.zj.osm.view.map.line;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.gms.maps.model.LatLng;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.model.pojo.Equip;
import com.zj.osm.model.pojo.Module;
import com.zj.osm.model.pojo.ModuleType;
import com.zj.osm.utils.AngleUtil;
import com.zj.osm.utils.SQLiteDatabaseUtils;
import com.zj.osm.view.BaseActivity;
import com.zj.osm.view.map.map.MapActivity;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.zj.osm.utils.MyUtils.Distance;


public class DistanceActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "DistanceActivity";
    private String aid, bid;
    private Long cid;
    private Spinner dis_sp;
    private EditText dis_ed_deng;
    private RelativeLayout dis_rl_deng;
    private EditText dis_ed_ding;
    private RelativeLayout dis_rl_ding;
    private Context context;
    private LatLng latLng_a, latLng_b;
    private Spinner dis_sp_sort;
    private Spinner dis_sp_equ;
    private Double length;
    private Point Point_a, Point_b;
    private List<Equip> equipList = new ArrayList<>();
    private List<Point> PointList = new ArrayList<>();
    private Spinner dis_sp_qsd;
    private RelativeLayout dis_rl_zi;
    private Project items;
    /**
     * 已知两点经纬度求方位角
     */
    public static double getAngle(double lon1, double lat1, double lon2, double lat2) {
        double fLat = Math.PI * (lat1) / 180.0;
        double fLng = Math.PI * (lon1) / 180.0;
        double tLat = Math.PI * (lat2) / 180.0;
        double tLng = Math.PI * (lon2) / 180.0;

        double degree = (Math.atan2(Math.sin(tLng - fLng) * Math.cos(tLat), Math.cos(fLat) * Math.sin(tLat) - Math.sin(fLat) * Math.cos(tLat) * Math.cos(tLng - fLng))) * 180.0 / Math.PI;
        if (degree >= 0) {
            return degree;
        } else {
            return 360 + degree;
        }
    }

    Line l;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_distance);
        context = this;
        initView();
        Intent intent = getIntent();
        l = intent.getParcelableExtra("line");
        aid = l.getStart_id();
        bid = l.getEnd_id();
        cid = l.getItem_id();
        length = Double.parseDouble(l.getLength());
        initData();
    }
    List<Line> xuanxinLine=new ArrayList<>();
    private void initData() {
        List<Line> oneLines= App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(l.getStart_id()),LineDao.Properties.End_id.eq(l.getEnd_id())).list();
        List<Line> twoLines=App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(l.getEnd_id()),LineDao.Properties.End_id.eq(l.getStart_id())).list();
        xuanxinLine.addAll(oneLines);
        xuanxinLine.addAll(twoLines);

        Point_a = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(aid)).build().list().get(0);
        Point_b = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(bid)).build().list().get(0);
        latLng_a = new LatLng(Double.valueOf(Point_a.getLatitude()), Double.valueOf(Point_a.getLongitude()));
        latLng_b = new LatLng(Double.valueOf(Point_b.getLatitude()), Double.valueOf(Point_b.getLongitude()));

        //Log.e(TAG, "addInitMap: " + Point_b.getMark());

        List<Point> adapter_dataq = new ArrayList<>();
        adapter_dataq.add(Point_a);
        adapter_dataq.add(Point_b);
        //适配器
        ArrayAdapter<Point> arr_adapterq = new ArrayAdapter<Point>(context, android.R.layout.simple_spinner_item, adapter_dataq);
        //设置样式
        arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dis_sp_qsd.setAdapter(arr_adapterq);
    }

    public List<Equip> getGuPiaoDaiMA(int str) {
        List<Equip> strings = new ArrayList<>();
        SQLiteDatabase db =  SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Equip equip = new Equip();
            equip.setId(cursor.getInt(0));
            equip.setName(cursor.getString(1));
            equip.setCode(cursor.getString(4));
            strings.add(equip);
        }
        cursor.close();
        
        return strings;
    }

    private void initView() {
        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        TextView activity_tv_save = findViewById(R.id.activity_tv_save);
        dis_sp = findViewById(R.id.dis_sp);
        dis_ed_deng = findViewById(R.id.dis_ed_deng);
        dis_rl_deng = findViewById(R.id.dis_rl_deng);
        dis_ed_ding = findViewById(R.id.dis_ed_ding);
        dis_rl_ding = findViewById(R.id.dis_rl_ding);
        Button dis_btn_save = findViewById(R.id.dis_btn_save);
        dis_sp_sort = findViewById(R.id.dis_sp_sort);
        dis_sp_equ = findViewById(R.id.dis_sp_equ);
        dis_btn_save.setOnClickListener(this);
        activity_tv_save.setOnClickListener(this);
        activity_ib_back.setOnClickListener(this);
        activity_tv_title.setText("插入");
        activity_tv_save.setText("取消");

        dis_sp_qsd = findViewById(R.id.dis_sp_qsd);
        dis_rl_zi = findViewById(R.id.dis_rl_zi);

        dis_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        dis_rl_deng.setVisibility(View.VISIBLE);
                        dis_rl_ding.setVisibility(View.GONE);
                        dis_rl_zi.setVisibility(View.GONE);
                        break;
                    case 1:
                        dis_rl_deng.setVisibility(View.GONE);
                        dis_rl_ding.setVisibility(View.VISIBLE);
                        dis_rl_zi.setVisibility(View.GONE);
                        break;
                    case 2:
                        dis_rl_deng.setVisibility(View.GONE);
                        dis_rl_ding.setVisibility(View.VISIBLE);
                        dis_rl_zi.setVisibility(View.VISIBLE);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dis_sp_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    final List<Equip> equip = getGuPiaoDaiMA(1);
                    List<String> adapter_data1 = new ArrayList<>();
                    for (int i = 0; i < equip.size(); i++) {
                        adapter_data1.add(equip.get(i).getName());
                        equipList.add(equip.get(i));
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter1 = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_data1);
                    //设置样式
                    arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    dis_sp_equ.setAdapter(arr_adapter1);
                } else if (position == 1) {
                    final List<Equip> equip2 = getGuPiaoDaiMA(2);
                    List<String> adapter_data3 = new ArrayList<>();
                    for (int i = 0; i < equip2.size(); i++) {
                        adapter_data3.add(equip2.get(i).getName());
                        equipList.add(equip2.get(i));
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter3 = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_data3);
                    //设置样式
                    arr_adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    dis_sp_equ.setAdapter(arr_adapter3);
                } else {
                    final List<Equip> equips = getGuPiaoDaiMA(4);
                    List<String> adapter_dataq = new ArrayList<>();
                    for (int i = 0; i < equips.size(); i++) {
                        adapter_dataq.add(equips.get(i).getName());
                        equipList.add(equips.get(i));
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapterq = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, adapter_dataq);
                    //设置样式
                    arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    dis_sp_equ.setAdapter(arr_adapterq);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_ib_back:
                MapActivity.isProgressShow=false;
                finish();
                break;
            case R.id.activity_tv_save:
                MapActivity.isProgressShow=false;
                finish();
                break;
            case R.id.dis_btn_save:
                if (!dis_ed_deng.getText().toString().trim().isEmpty()||!dis_ed_ding.getText().toString().trim().isEmpty()) {
                    save();
                }else{
                    ToastUtils.showShort("请填写指定内容");
                }
                //delete();
                break;
        }
    }


    /**
     * 点击踩点时进行的操作
     */
    private void save() {
        Point_b.setGlsb("");
        App.getInstances().getDaoSession().getPointDao().update(Point_b);
        List<LatLng> lngall;
        if ("等分模式".equals(dis_sp.getSelectedItem().toString().trim())) {
            int number = Integer.parseInt(dis_ed_deng.getText().toString().trim());
            if (number > 200) {
                ToastUtils.showShort("一次性踩点过多");
                return;
            } else {
                //等分模式：每一段都一样
                lngall = getDengLatLng(number+1);
            }
        } else if ("自由模式".equals(dis_sp.getSelectedItem().toString().trim())) {
            int number = Integer.parseInt(dis_ed_ding.getText().toString().trim());
            Point pointA = (Point) dis_sp_qsd.getSelectedItem();
            Point pointB = dis_sp_qsd.getSelectedItem() == Point_a ? Point_b : Point_a;

            lngall = getZiYouLatLng(number, pointA, pointB);
            Log.e("enenAA=",pointA.toString1());
            Log.e("enenBB=",pointB.toString1());



        } else {//
            int number = Integer.parseInt(dis_ed_ding.getText().toString().trim());
            if (number > length && number < 5) {
                ToastUtils.showShort("定的点距太大或太小");
                return;
            } else {
                int num = (int) (length / number);
                lngall = getDengLatLng(num);
            }
        }
        //添加点了
        addPointAll(lngall);
        //Long number = addInitMap(lngall, dis_sp_sort.getSelectedItem().toString().trim(), 1);


    }

    /**
     * @param lngall
     */
    private void addPointAll(List<LatLng> lngall) {
        List<Point> addPoint = new ArrayList<>();
        addPoint.add(Point_a);
        List<Point> allPoint = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(cid)).build().list();
        List<Line> lineList = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(cid)).build().list();
        for (int i = 1; i < lngall.size(); i++) {
            Point Point = new Point();
            Point.setId(null);
            UUID uuid = UUID.randomUUID();
            Point.setUid(uuid + "");
            Point.setHigh(Point_a.getHigh() + "");
            Point.setState("新建");
            Point.setProjectId(cid);
            Point.setNote("");
            Point.setLegendTypeKey(Point_a.getLegendTypeKey());
            if (l.getType().contains("电缆")) {
                Point.setMark("GD-" + (allPoint.size() + i + 1));
                Point.setEquipType_name("电缆拐点");
                Point.setName("电缆拐点");
                Point.setSblx("电缆拐点");
                Point.setWhether("4");
                Point.setIcon("DLGD");
                Point.setDefaultLineType("3");
            } else {
                Point.setMark("Z-" + (allPoint.size() + i + 1));
                Point.setEquipType_name("直线杆");
                Point.setSblx("直线杆");
                Point.setWhether("0");
                Point.setName("杆塔");
                Point.setIcon("ZXG");
                Point.setEquipType_id(1);
                Point.setDefaultLineType("1");
            }
            Point.setLatitude(lngall.get(i).latitude);
            Point.setLongitude(lngall.get(i).longitude);
            Point.setBatch("1");//批量

            if (i == lngall.size() - 1) {
                Point = Point_b;
            } else {//点的选型
                long id= App.getInstances().getDaoSession().getPointDao().insert(Point);
                ///查找关联点
                List<Point> towPointList=App.getInstances().getDaoSession().getPointDao().queryBuilder().whereOr(PointDao.Properties.Uid.eq(l.getStart_id()),PointDao.Properties.Uid.eq(l.getEnd_id())).list();
                Equipment equipment=getGlLine_ganxin(l,towPointList.get(0));
                if (equipment != null) {
                    List<Equipment> eqs = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(Point.getId()), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                    Log.e("444444", eqs.toString());
                    if (eqs == null || eqs.size() == 0) {
                        Equipment insertEquipment = new Equipment();
                        insertEquipment.setId(null);
                        insertEquipment.setName(equipment.getName());
                        insertEquipment.setTwoName(equipment.getTwoName());
                        insertEquipment.setThreeName(equipment.getThreeName());
                        insertEquipment.setFourName(equipment.getFourName());
                        insertEquipment.setQubie(equipment.getQubie());
                        insertEquipment.setNote(equipment.getNote());
                        insertEquipment.setPointId(id);
                        insertEquipment.setAmount(equipment.getAmount());
                        insertEquipment.setLever_id(equipment.getLever_id());
                        insertEquipment.setHead_id(equipment.getHead_id());
                        insertEquipment.setThreeId(equipment.getThreeId());
                        insertEquipment.setFourId(equipment.getFourId());
                        insertEquipment.setLineName(equipment.getLineName());
                        insertEquipment.setModule_code(equipment.getModule_code());
                        insertEquipment.setModuleID(equipment.getModuleID());
                        insertEquipment.setModuleTxt(equipment.getModuleTxt());
                        insertEquipment.setProjectId(equipment.getProjectId());
                        insertEquipment.setModuleTxt(equipment.getModuleTxt());
                        App.getInstances().getDaoSession().getEquipmentDao().insert(insertEquipment);
                    }
                }
            }
            addPoint.add(Point);

            //这里去设置选型
            for (int j = 0; j < xuanxinLine.size(); j++) {
                //添加线路操作
                Line line = new Line();
                BigDecimal bg = new BigDecimal(Distance(lngall.get(i - 1).latitude, lngall.get(i - 1).longitude, lngall.get(i).latitude, lngall.get(i).longitude)).setScale(2, RoundingMode.UP);
                double lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                line.setLength(lengths + "");
                line.setId(null);
                line.setItem_id(cid);
                line.setProjectId(cid);
                line.setCid(getUUID());
                line.setLatA(lngall.get(i - 1).latitude + "");
                line.setLonA(lngall.get(i - 1).longitude + "");
                line.setLatB(lngall.get(i).latitude + "");
                line.setLonB(lngall.get(i).longitude + "");
                line.setStart_id(addPoint.get(i - 1).getUid() + "");
                line.setEnd_id(addPoint.get(i).getUid() + "");
                line.setBackNum(l.getBackNum());
                line.setNum(l.getNum());
                line.setParallelPole("0");
                //TODO 这里修改了    line.setType("架空线路");
                line.setType(l.getType());
                line.setTypeId(l.getTypeId());
                int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
                line.setState(xuanxinLine.get(j).getState());
                //选型信息
                line.setName(xuanxinLine.get(j).getName());
                line.setModuleID(xuanxinLine.get(j).getModuleID());
                line.setModuleTxt(xuanxinLine.get(j).getModuleTxt());
                line.setTypes(xuanxinLine.get(j).getTypes());
                line.setTypeId(xuanxinLine.get(j).getTypeId());
                line.setType(xuanxinLine.get(j).getType());
                line.setMethodName(xuanxinLine.get(j).getMethodName());
                line.setPath(xuanxinLine.get(j).getPath());
                if(xuanxinLine.get(j).getLegendTypeKey()==null||xuanxinLine.get(j).getLegendTypeKey().isEmpty()){
                    line.setLegendTypeKey(getLineRemarker("高压架空线路"));
                }else{
                    line.setLegendTypeKey(xuanxinLine.get(j).getLegendTypeKey());
                }
                Long id= App.getInstances().getDaoSession().getLineDao().insert(line);
                //line.setName(id+ "#");
                //App.getInstances().getDaoSession().getLineDao().update(line);
//[Line{id=2, lineId='null', cid='78c41519-ac20-47cf-89fe-7a75835af96c', start_id='d9c69970-717e-4e8d-898d-32b8236191c9', end_id='f78f7c23-a083-4a73-b93c-98246f1ec39a', projectId=1, name='线路1#', category='null', type='架空线路', typeId='11', types='null', pipe_laying_state='null', state='新建', backNum='1', num='1', methodName='null', length='83.59', line_len='null', item_id=1, latA='39.05299733999537', latB='39.05350764819892', lonA='117.28819906711578', lonB='117.28890985250473', name_a=0, name_b=0, parallelPole='0', isT='null', path='null', moduleID='', moduleTxt='', legendTypeKey='TY_DHJKX', equipmentList=null, pointList=null, daoSession=com.zj.osm.entity.db.DaoSession@e2398ca, myDao=com.zj.osm.entity.db.LineDao@88f0563},
// Line{id=4, lineId='null', cid='af3cac85-5d69-464e-b785-91ae7dc02d78', start_id='5a32e1b8-f544-413c-a39f-e232c39ac5c4', end_id='5ed1a62f-dfec-4db6-be63-21b5125709c2', projectId=1, name='线路1#', category='null', type='电缆', typeId='12', types='null', pipe_laying_state='null', state='新建', backNum='1', num='1', methodName='null', length='278.99', line_len='null', item_id=1, latA='39.05401795640247', latB='39.05641738830031', lonA='117.28962063789368', lonB='117.28867650032043', name_a=0, name_b=0, parallelPole='0', isT='null', path='null', moduleID='', moduleTxt='', legendTypeKey='TY_DLD', equipmentList=null, pointList=null, daoSession=com.zj.osm.entity.db.DaoSession@e2398ca, myDao=com.zj.osm.entity.db.LineDao@88f0563},
// Line{id=6, lineId='null', cid='20f6081f-415a-438f-8496-dad5fa89b206', start_id='5ed1a62f-dfec-4db6-be63-21b5125709c2', end_id='c2e0bb9b-a91a-4d61-b9cd-48778dceff40', projectId=1, name='线路1#', category='null', type='电缆', typeId='12', types='null', pipe_laying_state='null', state='新建', backNum='1', num='null', methodName='null', length='166', line_len='null', item_id=1, latA='39.05641738830031', latB='39.057896164225305', lonA='117.28867650032043', lonB='117.28886425495148', name_a=0, name_b=0, parallelPole='0', isT='null', path='null', moduleID='', moduleTxt='', legendTypeKey='TY_DLD', equipmentList=null, pointList=null, daoSession=com.zj.osm.entity.db.DaoSession@e2398ca, myDao=com.zj.osm.entity.db.LineDao@88f0563}]

            }
        }
        //拿到所有的点
        for (int j = 0; j < xuanxinLine.size(); j++) {
            App.getInstances().getDaoSession().getLineDao().delete(xuanxinLine.get(j));
        }

        App.getInstances().getDaoSession().getLineDao().delete(l);
        Log.e("onbackproess","onback");
        MapActivity.isProgressShow=true;
        finish();
    }

    private Line getGline_xianlu(Line line) {
        List<Line> linesSslf = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.End_id.eq(line.getStart_id()), LineDao.Properties.Start_id.eq(line.getStart_id())).where(LineDao.Properties.ModuleID.notEq(""), LineDao.Properties.Type.eq("低压架空线路")).build().list();//where(LineDao.Properties.Type.like(line.getType())).where(LineDao.Properties.ModuleID.notEq("")).build().list();
        Log.e("lllllllll", linesSslf.toString());
        Log.e("llllllllineType==", line.getType());
        List<Line> lines = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.End_id.eq(line.getStart_id()), LineDao.Properties.Start_id.eq(line.getStart_id())).where(LineDao.Properties.Type.like("%" + line.getType() + "%"), LineDao.Properties.ModuleID.notEq("")).build().list();
        Log.e("llllllllllsss", lines.toString());
        if (lines.size() > 0) {//表示有线
            return lines.get(0);
        }

        if (items.getUnit() != null) {
            Line DefaultLine = new Line();
            String unit = items.getUnit();
            String[] defaultGanxing;
            if (line.getType().contains("架空")) {
                defaultGanxing = unit.split("\\|")[1].split(",");
            } else {//电缆
                defaultGanxing = unit.split("\\|")[2].split(",");
            }

            if (defaultGanxing.length > 0) {
                DefaultLine.setModuleID(defaultGanxing[0]);
                DefaultLine.setType(getEquipType(defaultGanxing[0]));
                DefaultLine.setMethodName(getEquipType(defaultGanxing[0]));
            } else {
                DefaultLine.setType(line.getType());

            }
            if (defaultGanxing.length > 1) {
                DefaultLine.setModuleTxt(getModuleLocal(defaultGanxing[1]) == null ? "" : getModuleLocal(defaultGanxing[1]).getModuleName());
                DefaultLine.setTypes(getModuleLocal(defaultGanxing[1]) == null ? "" : getModuleLocal(defaultGanxing[1]).getModuleName());
                DefaultLine.setTypeId(defaultGanxing[1]);

            }
            //辐射方式
            if (defaultGanxing.length > 2) {
                DefaultLine.setPath(defaultGanxing[2]);
            }
            return DefaultLine;
        }

        return null;
    }

    ///查询线的高压抵押线路的类型
    private String getEquipType(String reMarkerName) {
        String equipTypeName = "";
        SQLiteDatabase db =  SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        Log.e("sql", "select * from Module m where m.ModuleTypeKey =" + reMarkerName);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType m where m.id =" + "'" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            equipTypeName = cursor.getString(1);
        }

        cursor.close();
        

        return equipTypeName;
    }

    /**
     * 实现自由选点
     *
     * @param number 距离
     * @return 经纬度
     */
    private List<LatLng> getZiYouLatLng(int number, Point pointA, Point pointB) {
        List<LatLng> latLngList = new ArrayList<>();
        LatLng latLngA = new LatLng(pointA.getLatitude(), pointA.getLongitude());
        LatLng latLngB = new LatLng(pointB.getLatitude(), pointB.getLongitude());
        latLngList.add(latLngA);
        double degree = getAngle(latLngA.longitude, latLngA.latitude, latLngB.longitude, latLngB.latitude);
        AngleUtil angleUtil = new AngleUtil(latLngA.longitude, latLngA.latitude);
        latLngList.add(AngleUtil.getMyLatLng(angleUtil, number, degree));
        latLngList.add(latLngB);
        return latLngList;
    }

    @Override
    public void onBackPressed() {
        Log.e("onbackproess","onback");
        MapActivity.isProgressShow=false;
        super.onBackPressed();
    }

    /**
     * 计算两点之间定距的经纬度
     * 等距
     */
    private List<LatLng> getDingLatLng(int number) {
        int num = (int) (length / number);
        List<LatLng> latLngList = new ArrayList<>();
        double degree = getAngle(latLng_a.longitude, latLng_a.latitude, latLng_b.longitude, latLng_b.latitude);
        AngleUtil angleUtil = new AngleUtil(latLng_a.longitude, latLng_a.latitude);
        for (int j = 1; j < num + 1; j++) {
            latLngList.add(AngleUtil.getMyLatLng(angleUtil, number * j, degree));
        }
        return latLngList;
    }


    /**
     * 计算两点之间等距的经纬度
     */
    private List<LatLng> getDengLatLng(int number) {
        double aaa, bbb, ccc = 0, ddd = 0;
        List<LatLng> latLngs = new ArrayList<>();
        Log.e("hahahaA=", latLng_a.toString());
        Log.e("hahahaB=", latLng_b.toString());

        double mlat = (latLng_b.latitude - latLng_a.latitude) / number, mlng = (latLng_b.longitude - latLng_a.longitude) / number;
        for (int i = 0; i <= number; i++) {
            aaa = latLng_a.latitude + i * mlat;
            bbb = latLng_a.longitude + i * mlng;
            LatLng latLng = new LatLng(aaa, bbb);
            Log.e("hahaha=" + i, latLng.toString());
            latLngs.add(latLng);
        }
       /* for (int i = 1; i < number + 1; i++) {
            if (latLng_a.longitude > latLng_b.longitude && latLng_a.latitude > latLng_b.latitude) {
                aaa = (latLng_a.longitude - latLng_b.longitude) / (number);
                ccc = latLng_b.longitude + aaa * (i);
                bbb = (latLng_a.latitude - latLng_b.latitude) / (number);
                ddd = bbb * (i) + latLng_b.latitude;

            } else if (latLng_a.longitude < latLng_b.longitude && latLng_a.latitude < latLng_b.latitude) {
                aaa = (latLng_b.longitude - latLng_a.longitude) / (number);
                ccc = latLng_a.longitude + aaa * (i);
                bbb = (latLng_b.latitude - latLng_a.latitude) / (number);
                ddd = latLng_a.latitude + bbb * i;

            } else if (latLng_a.longitude > latLng_b.longitude && latLng_a.latitude < latLng_b.latitude) {
                aaa = (latLng_a.longitude - latLng_b.longitude) / (number);
                ccc = latLng_b.longitude + aaa * (number - i);
                bbb = (latLng_b.latitude - latLng_a.latitude) / (number);
                ddd = latLng_a.latitude + bbb * i;

            } else if (latLng_a.longitude < latLng_b.longitude && latLng_a.latitude > latLng_b.latitude) {
                aaa = (latLng_b.longitude - latLng_a.longitude) / (number);
                ccc = latLng_a.longitude + aaa * (i);
                bbb = (latLng_a.latitude - latLng_b.latitude) / (number);
                ddd = latLng_a.latitude - bbb * i;

            }

            latLngs.add(new LatLng(ddd, ccc));
        }*/
        return latLngs;
    }

    private Equipment getGlLine_ganxin(Line line, Point Point0) {
        items = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(cid)).build().list().get(0);
        String starId = line.getStart_id();
        //先取关联杆塔选型信息
        if (starId != null && Point0.getName().equals("杆塔")) {
            Point Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(starId)).build().unique();
            if (Point != null && Point0.getName().equals("杆塔") && Point.getName().equals("杆塔")) {
                Equipment ganxing = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(Point.getId()), EquipmentDao.Properties.Qubie.eq(0)).build().unique();
                return ganxing;
            }
        }

        //取默认选型
        if (items.getUnit() != null && Point0.getName().equals("杆塔")) {
            String unit = items.getUnit();
            String[] defaultGanxing = unit.split("\\|")[0].split(",");
            /**
             *  @Id
             *     private Long id;
             *     //添加设备名称
             *     private String name;
             *     //四级各个设备名称  four_name杆高
             *     private String two_name, three_name, four_name;
             *     //区分线还是点
             *     private int qubie;
             *     //添加设备备注信息
             *     private String note;
             *     //Point的id
             *     private Long point_id;
             *     //模块的数量
             *     private int amount;
             *     //杆头，杆型的ID
             *     private String lever_id, head_id;
             *     //四级各个ID               稍径
             *     private String three_id, four_id;
             *     //线设备名称
             *     private String lineName;
             *     //设备编号
             *     private String module_code;
             *     //去module查询的id
             *     private String ModuleID;
             *     //保存时候储存的信息
             *     private String ModuleTxt;
             *     //Item_ID
             *     private Long itemID;
             */
            //Equipment{id=133, name='水泥杆', two_name='水泥杆', three_name='非预应力,整根杆,10m,190mm,I', four_name='190mm', qubie=0, note='null', point_id=142, amount=1, lever_id='50000DG', head_id='50000DG', three_id='50000', four_id='10m', lineName='null', module_code='null', ModuleID='50000', ModuleTxt='非预应力,整根杆,10m,190mm,I', itemID=19}
            if (defaultGanxing.length > 1) {
                Module defaultModel = getModuleLocal(defaultGanxing[1]);
                ModuleType defultModuleType = getModuleType(defaultGanxing[0]);
                Equipment ganxing = new Equipment();
                ganxing.setQubie(0);
                ganxing.setModuleID(defaultModel.getModuleID());
                ganxing.setModuleTxt(defaultModel.getModuleName());
                ganxing.setName(defultModuleType.getName());
                ganxing.setThreeName(defaultModel.getModuleName());
                ganxing.setModuleTxt(defaultModel.getModuleName());
                ganxing.setProjectId(items.getId());
                ganxing.setLever_id(defaultGanxing[0]);
                ganxing.setHead_id(defaultGanxing[1]);
                //杆高和杆型 Modle表的ModuleName
                //资源文件来获取数据杆高
                String[] ganGaoArray = getResources().getStringArray(R.array.gangao_array);
                String[] ShaojingArray = getResources().getStringArray(R.array.shaojin_array);

                for (int i = 0; i < ganGaoArray.length; i++) {
                    if (defaultModel.getModuleName().contains(ganGaoArray[i])) {
                        ganxing.setFourId(ganGaoArray[i]);
                    }
                }
                for (int i = 0; i < ShaojingArray.length; i++) {
                    if (defaultModel.getModuleName().contains(ShaojingArray[i])) {
                        ganxing.setFourName(ShaojingArray[i]);

                    }
                }
                ganxing.setAmount(1);
                ganxing.setModule_code(defaultModel.getModuleCode());
                return ganxing;

            } else {
                return null;
            }
        }

        return null;
    }

    /**
     * @param
     * @return Equip
     */
    public ModuleType getModuleType(String ModuleTypeID) {
        ModuleType strings = null;
        try {
            SQLiteDatabase db =  SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType mt where mt.ModuleTypeID =" + "'" + ModuleTypeID + "'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                ModuleType equip = new ModuleType();
                equip.setModuleTypeID(cursor.getString(0));
                equip.setName(cursor.getString(1));
                equip.setModuleTypeKey(cursor.getString(2));
                strings = equip;
            }
            cursor.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }
    ///查询线的remark
    private Module getModuleLocal(String reMarkerName) {
        Module module_array = null;
        SQLiteDatabase db =  SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        Log.e("sql", "select * from Module m where m.ModuleTypeKey =" + reMarkerName);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module m where m.ModuleID =" + "'" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Module module = new Module();
            module.setModuleID(cursor.getString(0));
            module.setModuleName(cursor.getString(1));
            module.setModuleTypeKey(cursor.getString(2));
            module.setModuleCode(cursor.getString(3));
            module_array = module;
        }

        cursor.close();
        

        return module_array;
    }

    /**
     * 增加marker点
     */
    private Long addInitMap(List<LatLng> latLng, String name, int num) {


        List<Point> insertPoint = new ArrayList<>();
        Long number = null;
        if (num == 2) {//自由模式
            //🏪这个点去添加中间的点最后插入到了点点数据表中
            for (int i = 0; i < latLng.size(); i++) {
                Point PointIn = addMarker(latLng, i, name);
                if (PointIn != null) {
                    //说明添加点到数据库了将所有的点添加到集合里面。然后进行绘制线。
                    insertPoint.add(PointIn);
                    number = 1L;
                } else {
                    //说明添加错误了
                    number = -1L;
                }
            }
           /* PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Items_id.eq(cid)).build().list();
            Point_a.setGlsb(PointList.get(PointList.size() - 1).getMark());
            App.getInstances().getDaoSession().getPointDao().update(Point_a);*/
        } else {
            for (int i = latLng.size() - 1; i > -1; i--) {
                Point PointIn = addMarker(latLng, i, name);
                if (PointIn != null) {
                    //说明添加点到数据库了将所有的点添加到集合里面。然后进行绘制线。
                    insertPoint.add(PointIn);
                    number = 1L;
                } else {
                    //说明添加错误了
                    number = -1L;
                }
            }
            /*PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Items_id.eq(cid)).build().list();
            Point_a.setGlsb(PointList.get(PointList.size() - 1).getMark());
            App.getInstances().getDaoSession().getPointDao().update(Point_a);*/
        }
        //这里将最开始的点和最末尾点添加到第一和最后一个。
        if (number > 0) {//表明插入成功了点这里去获取所有点线
            //线的第一个点为插入时候第一个点。
            insertPoint.add(0, Point_a);
            //线的最后一个点为插入时候点最后一个点。
            insertPoint.add(Point_b);
            //TODO 这里去删除线而且去链接所有的点。
            App.getInstances().getDaoSession().getLineDao().delete(l);
            insertLineToDB(insertPoint);


        }

        return number;

    }

    /**
     * 进行去连线，画出所有点线。然后去添加到线到db中
     *
     * @param insertPoint 等分，等距，自由模式，中间所添加点所有点。
     */
    private void insertLineToDB(List<Point> insertPoint) {
        Log.e("allPoint=", insertPoint.toString());
        List<Line> linesAll = new ArrayList<>();
        for (int i = 0; i < insertPoint.size() - 1; i++) {
            Line line = new Line();
            line.setId(null);
            line.setItem_id(cid);
            line.setLatA(insertPoint.get(i).getLatitude()+"");
            line.setLonA(insertPoint.get(i).getLongitude()+"");
            line.setLatB(insertPoint.get(i + 1).getLatitude()+"");
            line.setLonB(insertPoint.get(i + 1).getLongitude()+"");
            line.setStart_id(insertPoint.get(i).getUid());
            line.setEnd_id(insertPoint.get(i + 1).getUid());
            //设置档距,第一个点和第二个点点一起计算距离。
            BigDecimal bg = new BigDecimal(Distance(Double.valueOf(insertPoint.get(i).getLatitude() + ""), Double.valueOf(insertPoint.get(i).getLongitude() + ""), Double.valueOf(insertPoint.get(i + 1).getLatitude()), Double.valueOf(insertPoint.get(i - 1).getLongitude()))).setScale(2, RoundingMode.UP);
            double lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            line.setLength(lengths + "");
            //会路数
            line.setBackNum("1");
            if (insertPoint.get(i).getName().equals("杆塔")) {
                line.setType("架空线路");
                line.setTypeId("11");
            } else {
                line.setType("电缆");
                line.setTypeId("42");
            }
            line.setBackNum("1");
            line.setState("新建");
            line.setNum("1");
            int mad = (int) (insertPoint.get(i + 1).getId() + 1);
            if (line.getType().equals("架空线路")) {
                line.setName("架空线路-" + mad + "#");
            } else {
                line.setName("电缆-" + mad + "#");
            }
            App.getInstances().getDaoSession().getLineDao().insert(line);


        }
    }

    /**
     * @param latLng 经纬度集合
     * @param i      下标
     * @param name   名称
     */
    private Point addMarker(List<LatLng> latLng, int i, String name) {
        Log.e("allpoint=", Point_a.toString1());
        //Point{id=3, equ_id=1, high='1.1', old='新建', lineType='null', linetype='null', items_id=1, note='备注信息：', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='39.08279969943878', lon='117.09880038366641', weizhi='null', dangju=111.59, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='9db86484-5b00-4386-98fc-8a2dd1c258f2', length='null', width='null', address='null'}
        double lengths;
        Point Point = new Point();
        Point.setId(null);
        UUID uuid = UUID.randomUUID();
        Point.setUid(uuid + "");
        Point.setProjectId(cid);
        Point.setName(name);
        //Point.setSbbh(dis_sp_equ.getSelectedItem().toString().trim());
        Point.setState("新建");
        if (i == 0) {
            Point.setGlsb(Point_a.getMark());
            Point.setLatA(latLng_a.latitude + "");
            Point.setLonA(latLng_a.longitude + "");
            Point.setLatB(latLng.get(i).latitude + "");
            Point.setLonB(latLng.get(i).longitude + "");
        } else if (i < latLng.size()) {
            Point.setGlsb(Point_a.getMark());
            Point.setLatA(latLng.get(i - 1).latitude + "");
            Point.setLonA(latLng.get(i - 1).longitude + "");
            Point.setLatB(latLng.get(i).latitude + "");
            Point.setLonB(latLng.get(i).latitude + "");
        } else {
            Point.setGlsb(Point_b.getMark());
            Point.setLatA(latLng.get(i).latitude + "");
            Point.setLonA(latLng.get(i).latitude + "");
            Point.setLatB(latLng_b.latitude + "");
            Point.setLonB(latLng_b.latitude + "");
        }
        Point.setLatitude(latLng.get(i).latitude);
        Point.setLongitude(latLng.get(i).longitude);
        Point.setHigh("");
        Point.setBatch("1");//是批量踩点就是1，否则为0
        Point.setSblx(dis_sp_equ.getSelectedItem().toString().trim());
        //是没有地形点的。所有不用管。
        for (int index = 0, len = equipList.size(); index < len; index++) {
            if (dis_sp_equ.getSelectedItem().toString().trim().equals(equipList.get(index).getName())) {
                Point.setEquipType_id(equipList.get(index).getId());
                Point.setSblx(equipList.get(index).getName());
                //计算当前点得个数+1
            }
        }
        Point.setState("新建");
        //设置关联关系？
        //点上面设置档距这里需要区分
        /*BigDecimal bg = new BigDecimal(Distance(Double.valueOf(latLng.get(i).latitude + ""), Double.valueOf(latLng.get(i).longitude + ""), Double.valueOf(PointList.get(PointList.size() - 1).getLatitude()), Double.valueOf(PointList.get(PointList.size() - 1).getLongitude()))).setScale(2, RoundingMode.UP);
        lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();*/
        Point.setLength("");
        if (App.getInstances().getDaoSession().getPointDao().insert(Point) > 0) {
            return Point;
        } else {
            return null;
        }

       /* List<Point> PointList1 = App.getInstances().getDaoSession().getPointDao().queryBuilder().build().list();

        for (int j = 0; j < equipList.size(); j++) {
            Long mid = PointList1.get(PointList1.size() - 1).getId() + 1;
            Point.setMark(equipList.get(j).getCode() + "-" + mid);

        }

        Point.setName(name);
        Point.setSbbh(dis_sp_equ.getSelectedItem().toString().trim());
        Point.setOld("新建");

        if (name.equals("地形点")) {
            Point.setGlsb("");
            Point.setWhether("1");
            Point.setCategory("条状物");
        } else {
            Point.setWhether("0");
            final List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Items_id.eq(cid), PointDao.Properties.Whether.eq("0")).build().list();
            if (PointList.size() > 0) {
                //这里已经知道了起始点和末尾点，然后进行点的所有计算。
                //Log.e(TAG, "addInitMap: " + PointList.get(PointList.size() - 1).getMark());
                Point.setGlsb(PointList.get(PointList.size() - 1).getMark());
                BigDecimal bg = new BigDecimal(Distance(Double.valueOf(latLng.get(i).latitude + ""), Double.valueOf(latLng.get(i).longitude + ""), Double.valueOf(PointList.get(PointList.size() - 1).getLatitude()), Double.valueOf(PointList.get(PointList.size() - 1).getLongitude()))).setScale(2, RoundingMode.UP);
                lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                Point.setLength(lengths + "");
                Point PointL = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Mark.eq(Point.getGlsb())).build().list().get(0);
                List<Line> lineList = App.getInstances().getDaoSession().getLineDao().queryBuilder().build().list();
                Line line = new Line();
                line.setId(null);
                line.setItem_id(cid);
                line.setLatA(latLng.get(i).latitude + "");
                line.setLonA(latLng.get(i).longitude + "");
                line.setLatB(PointList.get(PointList.size() - 1).getLatitude());
                line.setLonB(PointList.get(PointList.size() - 1).getLongitude());
                line.setStart_id(Point.getUid());
                line.setEnd_id(PointL.getUid());
                line.setLength(lengths + "");
                if (PointList.get(PointList.size() - 1).getName().equals("杆塔") && Point.getName().equals("杆塔")) {
                    line.setType("架空线路");
                    line.setType_Id("11");
                } else {
                    line.setType("电缆");
                    line.setType_Id("42");
                }
                line.setBackNum("1");
                line.setStatue("新建");
                line.setNum("1");
                if (lineList.size() > 0) {
                    int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
                    if (line.getType().equals("架空线路"))
                        line.setName("架空线路-" + mad + "#");
                    else
                        line.setName("电缆-" + mad + "#");
                } else {
                    if (line.getType().equals("架空线路"))
                        line.setName("架空线路-" + 1 + "#");
                    else
                        line.setName("电缆-" + 1 + "#");
                }
                App.getInstances().getDaoSession().getLineDao().insert(line);
                Point.setDangju(lengths);
            }

        }

        return App.getInstances().getDaoSession().getPointDao().insert(Point);*/
    }
    ///查询线的remark
    private String getLineRemarker(String reMarkerName) {
        Log.e("legengTypeKeee1", reMarkerName);
        String ReMark = "";
        SQLiteDatabase db =  SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType  where name='" + reMarkerName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
                ReMark = cursor.getString(6);
                break;
        }
        cursor.close();
        
        Log.e("legengTypeKeee2", ReMark);
        return ReMark;
    }
    /**
     * 获取UUID
     *
     * @return uuid
     */
    private String getUUID() {
        return UUID.randomUUID() + "";
    }
}
